<template>
  <div class="Search">
    <!-- ------------------------------------------------------------------------ -->
    <!-- 列表-->
    <!-- :data 绑定渲染的数据；border: 边框; -->
    <el-table :data="list" stripe border style="width: 100%">
      <!--type="index" 获取索引值，从1开始； label 显示的标题; prop 数据字段名； width 列的宽度 -->
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="spectrumName" label="曲谱名称" width="250"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column label="操作" width="500">
        <template slot-scope="scope">
          <el-button type="primary" round icon="el-icon-view" @click="pu(scope.row.spectrumId)"></el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            circle
            @click="handleEdit(scope.row.spectrumId)"
          ></el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            circle
            @click="deleById(scope.row.spectrumId)"
          ></el-button>
          <el-upload
            :show-file-list="false"
            multiple
            style="display:inline-flex;margin-left:20px"
            class="upload-demo"
            :before-upload="handleBeforeUpload"
            :on-success="onSuccess"
            :data="{spectrumId:scope.row.spectrumId}"
            action="http://localhost:8181/spectrum/img"
          >
            <el-button type="success" plain round :icon="importDataBtnIcon">{{importDataBtnText}}</el-button>
          </el-upload>
          <el-upload
            :show-file-list="false"
            multiple
            style="display:inline-flex;margin-left:20px"
            class="upload-demo"
            :before-upload="handleBeforeUpload"
            :on-success="onSuccess"
            :data="{spectrumId:scope.row.spectrumId}"
            action="http://localhost:8181/spectrum/updateImg"
          >
            <el-button type="primary" plain round :icon="importDataBtnIcon">更新图片</el-button>
          </el-upload>
        </template>
      </el-table-column>
    </el-table>
    <!-- 下方页码区域-------------------------------------------------------------------- -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="current"
      :page-sizes="[5,8,10]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- ------------点击弹出的页面 ------------------------------------------------------>
    <el-dialog title :visible.sync="dialogFormVisible" width="400px">
      <el-form class="addform" ref="form" :model="form" label-width="100px">
        <el-form-item label="曲谱名" prop="name">
          <el-input v-model="form.spectrumName" style="width:230px"></el-input>
        </el-form-item>
        <el-form-item label="作者名" prop="author">
          <el-input v-model="form.author" style="width:230px"></el-input>
        </el-form-item>
        <el-form-item label="曲谱大类型" prop="category">
          <el-input disabled style="width:230px" v-model="form.category"></el-input>
        </el-form-item>
        <el-form-item label="曲谱小类型" prop="subcategory">
          <el-input disabled style="width:230px" v-model="form.subcategory"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateData()">保存</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- ------------------------------曲谱------------------------------- -->
    <el-dialog :visible.sync="dialogVisible" width="85%">
      <el-image v-for="url in urls" :key="url" :src="url" lazy></el-image>
    </el-dialog>
  </div>
</template>

<script>
import spectrumApi from "@/api/spectrum";
import Bus from '@/bus'
export default {
  data() {
    return {
      list: [], //列表数据
      //----------------------------------------------分页
      total: 0, // 总记录数
      current: 1, // 当前页, 默认第1页
      size: 5, // 每页显示条数， 10条
      //---------------------------------------------搜索框
      // searchMap: {
      //   spectrumName: null,
      //   author: null
      // },
      //--------------------------------------------------控制对话框是否
      dialogFormVisible: false, // 控制新增对话框
      dialogVisible: false,
      //--------------------------------------------------新增对话框的数据绑定源
      form: {
        spectrumId: null, //增加id
        spectrumName: "",
        author: "",
        category: "",
        subcategory: ""
      },
      urls: [""],
      drawer: false,
      //上传图片
      importDataBtnText: "上传图片",
      importDataBtnIcon: "el-icon-circle-plus-outline"
    };
  },

  // 钩子函数获取数据
  created() {
    Bus.$on("click", resp => {
      console.log("通过中央事件总线获取到的数据-------------", resp); //　注意：发送和监听的事件名称必须一致，target就是获取的数据，可以不写target。只要你喜欢叫什么都可以（当然了，这一定要符合形参变量的命名规范）
      this.list = resp.data.records
   });
  },

  beforeDestroy() {
    Bus.$off("click");
  },
  methods: {
    //列表获取
    getData() {
     Bus.$on("click", resp => {
      console.log("通过中央事件总线获取到的数据-------------", resp); //　注意：发送和监听的事件名称必须一致，target就是获取的数据，可以不写target。只要你喜欢叫什么都可以（当然了，这一定要符合形参变量的命名规范）
      this.list = resp.data.records
   });
    },

    //分页改变
    handleSizeChange(val) {
      this.size = val;
      this.getData();
    },
    //分页改变
    handleCurrentChange(val) {
      this.current = val;
      this.getData();
    },

    // 表单重置，
    // 在 el-form-item 标签属性 prop 上, 指定了字段名, 重置才会生效
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getData();
    },
    // 打开新增窗口
    handleAdd() {
      console.log("-----打开新增/编辑----");
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["form"].resetFields();
      });
    },
    //新增
    addData() {
      // 验证通过，提交添加
      spectrumApi.add(this.form).then(response => {
        // const resp = response.data
        const resp = response;
        console.log(resp);
        // 提示信息
        this.$message({
          message: "新增成功",
          type: "success"
        });
        if (resp) {
          this.getData();
          this.dialogFormVisible = false;
          console.log("--------------新增数据成功------------");
        } else {
          // 验证不通过
          this.$message({
            message: resp.msg,
            type: "warning"
          });
        }
      });
    },
    //删除
    deleById(spectrumId) {
      this.$confirm("确认删除这条记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          console.log("确认删除");
          // 确认
          spectrumApi.deletespectrumById(spectrumId).then(response => {
            const resp = response.data;
            //提示信息
            this.$message({
              message: "删除成功",
              type: "success"
            });
            // 删除成功，刷新列表
            this.getData();
          });
        })
        .catch(() => {
          // 取消删除，不理会
          console.log("取消");
        });
    },
    //--------------------------------------------------------------编辑功能（打开窗口+保存）
    // 打开编辑窗口
    handleEdit(spectrumId) {
      // 重用打开新增窗口方法, 不要少了 this
      this.handleAdd();
      // 查询数据
      spectrumApi.getSpectrumById(spectrumId).then(response => {
        console.log(response);
        const resp = response.data.data;
        this.form = resp;
        console.log("----------------------", spectrumId);
      });
    },
    // 更新数据
    updateData() {
      // 验证通过，提交
      spectrumApi.update(this.form).then(resp => {
        if (resp.data.code == 100) {
          //提示信息
          this.$message({
            type: "success",
            message: resp.data.msg
          });
          this.getData(); // 刷新列表数据
          this.dialogFormVisible = false; // 关闭窗口
        } else {
          this.$message({
            type: "error",
            message: "修改失败"
          });
          this.getData(); // 刷新列表数据
          this.dialogFormVisible = false; // 关闭窗口
        }
      });
    },
    //点击曲谱的动作
    pu(spectrumId) {
      console.log("------当前琴谱的id：", spectrumId);
      spectrumApi.getURLById(spectrumId).then(response => {
        console.log(response);
        this.urls = response.data.data;
        if (response.data == "") {
          alert("暂无图片，请先上传");
          this.dialogVisible = false;
        } else {
          this.dialogVisible = true;
          // this.drawer = true;
        }
      });
    },

    onSuccess(response, file, fileList) {
      this.importDataBtnText = "上传图片";
      this.importDataBtnIcon = "el-icon-circle-plus-outline";
      this.$message({
        type: "success",
        message: response.msg
      });
    },
    handleBeforeUpload(file) {
      console.log("文件上传前的方法");
      console.log(file);
      this.importDataBtnText = "上传中";
      this.importDataBtnIcon = "el-icon-loading";
    }
  }
};
</script>


<style scoped>
</style>